package com.sxygsj.android.personnelscreen.plugin_jiguang.webserver

import android.app.Service
import android.content.Intent
import android.os.IBinder
import android.util.Log
import com.yanzhenjie.andserver.AndServer
import com.yanzhenjie.andserver.Server
import java.net.InetAddress
import java.util.concurrent.Executors
import java.util.concurrent.ScheduledExecutorService
import java.util.concurrent.TimeUnit

class WebServerService : Service() {
    val PORT = 8000
    val TAG = "ceshi"
    private var webServerListener: ScheduledExecutorService= Executors.newScheduledThreadPool(1)
    lateinit var mAndserver: Server

    override fun onCreate() {
        super.onCreate()

        try {
            mAndserver = AndServer.webServer(this)
                .inetAddress(InetAddress.getByName("0.0.0.0"))
                .port(PORT)
                .timeout(100, TimeUnit.SECONDS)
                .listener(object :Server.ServerListener{
                    override fun onStarted() {
                        Log.i(TAG,"AndServer启动")
                    }

                    override fun onStopped() {
                        Log.i(TAG,"AndServer停止")
                    }

                    override fun onException(e: Exception) {
                        Log.i(TAG,e.toString())
                    }

                }).build()

        }catch (e:Exception){

        }
        webServerListener.scheduleAtFixedRate({
            if (!mAndserver.isRunning){
                mAndserver.startup()

            }
        },1000,1000,TimeUnit.MILLISECONDS)

    }
    override fun onBind(intent: Intent): IBinder? {
       return null
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        if (!mAndserver.isRunning){
            mAndserver.startup()
        }
        return START_STICKY
    }

    override fun onDestroy() {
        super.onDestroy()
        if (mAndserver.isRunning){
            mAndserver.shutdown()
        }
    }
}